
// arduino script for singlee MMG input, focusing on the RMSing of values every 
// 100 or so samples.
// Written by Edward Brial 

#include <Wire.h>
#include <math.h>
#include "filter.h"

#define RMSsize 50      // Sample size of RMS window, up here so it's easy to change

//call prototypes & global variables
//int RMSfun (short* readings, int length);
unsigned long lastmeasure;
int RMSfinal;
short tempread[RMSsize];
short filtarray[RMSsize];


void setup(){
	Wire.begin(0x02); //the address will need to be specified at some point!!
	Wire.onRequest(sendRMS);
}

void loop(){
	int i;

	while (1) {
		for (i=0 ; i < RMSsize; i++ ) { //i++ = unit increment every loop
			lastmeasure = micros(); // starts lastmeasure from micros current timing point
			tempread[i] = analogRead(A0);
			while (micros() < lastmeasure + 1250) ; // waits for 1250microsecs before next reading
		}
                filter(tempread, filtarray, RMSsize); //Data array will be filtered
		RMSfinal = RMSfun(filtarray, RMSsize);   //RMS value of Data Array
	}
}


// I2C subroutine
void sendRMS (void) {
	Wire.write(RMSfinal); // stores the RMSfinal value in the wire send buffer, ready for the call!
	Wire.endTransmission();   // is this part necessary? 
}

// function to be written to take the moving rms of each temp sample.
int RMSfun (short* readings, int length){
	int j;
	int Sum = 0;
	int RmsVal;

	for (j=0 ; j < length; j++) {
		readings[j] = readings[j]*readings[j]; //squares all the individual values. rms = sqrt(1/n(sum(xi^2)))
		Sum = Sum + readings[j];
	}
	RmsVal = sqrt(Sum/length);

	return RmsVal;
}




